import 'package:flutter/material.dart';
import '../models/acceptance_form.dart';
import '../services/acceptance_service.dart';
import '../services/pdf_service.dart';
import '../services/excel_service.dart';
import 'acceptance_form_screen.dart';
import 'acceptance_detail_screen.dart';
import 'acceptance_progress_screen.dart';
import 'package:path_provider/path_provider.dart';
import 'package:open_file/open_file.dart';

class AcceptanceListScreen extends StatefulWidget {
  const AcceptanceListScreen({super.key});

  @override
  State<AcceptanceListScreen> createState() => _AcceptanceListScreenState();
}

class _AcceptanceListScreenState extends State<AcceptanceListScreen> {
  final AcceptanceService _acceptanceService = AcceptanceService();
  final PdfService _pdfService = PdfService();
  final ExcelService _excelService = ExcelService();
  List<AcceptanceForm> _forms = [];
  List<AcceptanceForm> _filteredForms = [];
  bool _isLoading = true;
  String _searchQuery = '';
  DateTime? _startDate;
  DateTime? _endDate;
  int _statusFilter = 0; // 0: 全部, 1: 待处理, 2: 处理中, 3: 已完成

  @override
  void initState() {
    super.initState();
    _loadForms();
  }

  Future<void> _loadForms() async {
    setState(() => _isLoading = true);
    try {
      final forms = await _acceptanceService.getAcceptanceForms();
      if (mounted) {
        setState(() {
          _forms = forms;
          _filteredForms = forms;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('加载受理单失败: $e'),
            action: SnackBarAction(
              label: '重试',
              onPressed: _loadForms,
            ),
          ),
        );
      }
    }
  }

  void _filterForms() {
    setState(() {
      _filteredForms = _forms.where((form) {
        // 搜索条件
        final matchesSearch = _searchQuery.isEmpty ||
            form.formNumber.toLowerCase().contains(_searchQuery.toLowerCase()) ||
            form.applicantName.toLowerCase().contains(_searchQuery.toLowerCase()) ||
            form.respondentName.toLowerCase().contains(_searchQuery.toLowerCase());

        // 日期范围条件
        final matchesDate = (_startDate == null || form.acceptanceDate.isAfter(_startDate!)) &&
            (_endDate == null || form.acceptanceDate.isBefore(_endDate!));

        // 状态条件
        final matchesStatus = _statusFilter == 0 || form.status == _statusFilter;

        return matchesSearch && matchesDate && matchesStatus;
      }).toList();
    });
  }

  Future<void> _selectDateRange() async {
    final DateTimeRange? picked = await showDateRangePicker(
      context: context,
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
      initialDateRange: _startDate != null && _endDate != null
          ? DateTimeRange(start: _startDate!, end: _endDate!)
          : null,
    );

    if (picked != null) {
      setState(() {
        _startDate = picked.start;
        _endDate = picked.end;
      });
      _filterForms();
    }
  }

  void _showFilterDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('筛选条件'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 状态筛选
            DropdownButtonFormField<int>(
              value: _statusFilter,
              decoration: const InputDecoration(
                labelText: '状态',
                border: OutlineInputBorder(),
              ),
              items: const [
                DropdownMenuItem(value: 0, child: Text('全部')),
                DropdownMenuItem(value: 1, child: Text('待处理')),
                DropdownMenuItem(value: 2, child: Text('处理中')),
                DropdownMenuItem(value: 3, child: Text('已完成')),
              ],
              onChanged: (value) {
                setState(() => _statusFilter = value!);
                _filterForms();
                Navigator.pop(context);
              },
            ),
            const SizedBox(height: 16),
            // 日期范围选择
            ElevatedButton(
              onPressed: _selectDateRange,
              child: Text(
                _startDate != null && _endDate != null
                    ? '${_startDate!.year}-${_startDate!.month}-${_startDate!.day} 至 ${_endDate!.year}-${_endDate!.month}-${_endDate!.day}'
                    : '选择日期范围',
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _exportToExcel() async {
    setState(() => _isLoading = true);
    try {
      final forms = _filteredForms.map((form) => {
        'formNumber': form.formNumber,
        'date': form.acceptanceDate.toString().split(' ')[0],
        'applicantInfo': {
          'name': form.applicantName,
          'contact': form.applicantPhone,
          'idNumber': form.applicantIdCard,
        },
        'respondentInfo': {
          'name': form.respondentName,
          'contact': form.respondentPhone,
          'idNumber': form.respondentIdCard,
        },
        'disputeDescription': form.disputeDescription,
        'acceptorName': form.acceptorName,
        'acceptorUnit': form.acceptorUnit,
        'acceptorPhone': form.acceptorPhone,
        'status': _getStatusText(form.status),
      }).toList();

      final filePath = await _excelService.exportAcceptanceFormsToExcel(forms);
      if (mounted) {
        setState(() => _isLoading = false);
        await OpenFile.open(filePath);
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导出失败: $e')),
        );
      }
    }
  }

  Future<void> _printForm(AcceptanceForm form) async {
    setState(() => _isLoading = true);
    try {
      final filePath = await _pdfService.generateAcceptanceFormPdf(
        formNumber: form.formNumber,
        date: form.acceptanceDate.toString().split(' ')[0],
        applicantInfo: {
          'name': form.applicantName,
          'contact': form.applicantPhone,
          'idNumber': form.applicantIdCard,
        },
        respondentInfo: {
          'name': form.respondentName,
          'contact': form.respondentPhone,
          'idNumber': form.respondentIdCard,
        },
        disputeDescription: form.disputeDescription,
        acceptorName: form.acceptorName,
        acceptorUnit: form.acceptorUnit,
        acceptorPhone: form.acceptorPhone,
      );
      
      if (mounted) {
        setState(() => _isLoading = false);
        await OpenFile.open(filePath);
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('打印失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8FAFC),
      body: Column(
        children: [
          // 顶部操作栏
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, 5),
                ),
              ],
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '受理单列表',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF1E293B),
                  ),
                ),
                Row(
                  children: [
                    TextButton.icon(
                      onPressed: _exportToExcel,
                      icon: const Icon(Icons.download),
                      label: const Text('导出数据'),
                    ),
                    const SizedBox(width: 16),
                    ElevatedButton.icon(
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const AcceptanceFormScreen(),
                          ),
                        ).then((_) => _loadForms());
                      },
                      icon: const Icon(Icons.add),
                      label: const Text('新建受理单'),
                    ),
                  ],
                ),
              ],
            ),
          ),
          // 搜索和筛选栏
          Container(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                // 搜索框
                Expanded(
                  child: TextField(
                    decoration: InputDecoration(
                      hintText: '搜索受理单号/申请人/被申请人',
                      prefixIcon: const Icon(Icons.search),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    onChanged: (value) {
                      setState(() => _searchQuery = value);
                      _filterForms();
                    },
                  ),
                ),
                const SizedBox(width: 16),
                // 筛选按钮
                IconButton(
                  onPressed: _showFilterDialog,
                  icon: const Icon(Icons.filter_list),
                  tooltip: '筛选',
                ),
              ],
            ),
          ),
          // 列表内容
          Expanded(
            child: _isLoading
                ? const Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        CircularProgressIndicator(),
                        SizedBox(height: 16),
                        Text('正在加载受理单...'),
                      ],
                    ),
                  )
                : _filteredForms.isEmpty
                    ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            const Icon(
                              Icons.inbox,
                              size: 64,
                              color: Colors.grey,
                            ),
                            const SizedBox(height: 16),
                            const Text(
                              '暂无数据',
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.grey,
                              ),
                            ),
                            const SizedBox(height: 8),
                            TextButton.icon(
                              onPressed: _loadForms,
                              icon: const Icon(Icons.refresh),
                              label: const Text('刷新'),
                            ),
                          ],
                        ),
                      )
                    : RefreshIndicator(
                        onRefresh: _loadForms,
                        child: ListView.builder(
                          padding: const EdgeInsets.all(16),
                          itemCount: _filteredForms.length,
                          itemBuilder: (context, index) {
                            final form = _filteredForms[index];
                            return Card(
                              margin: const EdgeInsets.only(bottom: 16),
                              child: ListTile(
                                title: Text(
                                  form.formNumber,
                                  style: const TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Color(0xFF1E293B),
                                  ),
                                ),
                                subtitle: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const SizedBox(height: 8),
                                    Text('申请人: ${form.applicantName}'),
                                    Text('被申请人: ${form.respondentName}'),
                                    Text('受理日期: ${form.acceptanceDate.toString().split(' ')[0]}'),
                                    const SizedBox(height: 8),
                                    Container(
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 8,
                                        vertical: 4,
                                      ),
                                      decoration: BoxDecoration(
                                        color: _getStatusColor(form.status),
                                        borderRadius: BorderRadius.circular(4),
                                      ),
                                      child: Text(
                                        _getStatusText(form.status),
                                        style: const TextStyle(
                                          color: Colors.white,
                                          fontSize: 12,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    IconButton(
                                      icon: const Icon(Icons.timeline),
                                      onPressed: () async {
                                        final result = await Navigator.push<bool>(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) => AcceptanceProgressScreen(
                                              formNumber: form.formNumber,
                                            ),
                                          ),
                                        );
                                        if (result == true) {
                                          _loadForms(); // 刷新列表
                                        }
                                      },
                                    ),
                                    IconButton(
                                      icon: const Icon(Icons.visibility),
                                      onPressed: () async {
                                        final result = await Navigator.push<bool>(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) => AcceptanceDetailScreen(
                                              formNumber: form.formNumber,
                                            ),
                                          ),
                                        );
                                        if (result == true) {
                                          _loadForms(); // 刷新列表
                                        }
                                      },
                                    ),
                                    IconButton(
                                      icon: const Icon(Icons.print_rounded),
                                      onPressed: () => _printForm(form),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
                      ),
          ),
        ],
      ),
    );
  }

  Color _getStatusColor(int status) {
    switch (status) {
      case 1:
        return const Color(0xFFF59E0B); // 待处理 - 橙色
      case 2:
        return const Color(0xFF3B82F6); // 处理中 - 蓝色
      case 3:
        return const Color(0xFF10B981); // 已完成 - 绿色
      default:
        return Colors.grey;
    }
  }

  String _getStatusText(int status) {
    switch (status) {
      case 1:
        return '待处理';
      case 2:
        return '处理中';
      case 3:
        return '已完成';
      default:
        return '未知状态';
    }
  }
} 